<template>
    <h3>ref全家桶</h3>
    <div v-on:click="changeObj1">shallowRef:{{obj1}}</div>
    <div v-on:click="changeObj2">customRef:{{mystr}}</div>
</template>
<script lang="ts" setup>
import { customRef, isRef, isShallow, Ref, ref, shallowRef, triggerRef } from 'vue';


// 1  isRef 判断是不是一个ref对象
let str: Ref<number> = ref(1);
let str2: number = 9;
console.log('isRef:', isRef(str), isRef(str2));




// 2 shallowRef 创建一个跟踪自身 .value 变化的 ref，但不会使其值也变成响应式的
interface Obj {
    name: string,
    hoddy: {
        color: string
    }
}
let obj1 = shallowRef<Obj>({
    name: 'zhansan',
    hoddy: {
        color: 'red'
    }
});
let changeObj1 = () => {
    obj1.value.name = 'zhansan---1';
    obj1.value.hoddy.color = 'green';
    // 强制更新
    triggerRef(obj1);

    // obj1.value = {
    //     name: 'lisi',
    //     hoddy: {
    //         color: 'yellow'
    //     }   
    // }
    console.log('changeObj1', obj1, isShallow(obj1));
};



// customRef customRef 是个工厂函数要求我们返回一个对象 并且实现 get 和 set
const myRef = <T>(value:T) => {
    return customRef((track, trigger) => {
        return {
            get() {
                console.log('get-->')
                track();
                return value;
            },
            set(newValue: T) { 
                console.log('set--->')
                value = newValue;
                trigger();
            }
        }
    })
};
let mystr = myRef('你好');
let changeObj2 = () => {
    mystr.value = 'hello!!!';
}


</script>
 <style scoped lang="less">
 
 </style>